package com.whsxt.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 数据库连接工具类
 * @Author 武汉尚学堂
 */
public abstract class JdbcUtil {

    /**
     * 连接驱动
     */
    private static final String DRIVER;
    /**
     * 数据库连接地址
     */
    private static final String URL;
    /**
     * 用户名
     */
    private static final String USERNAME;
    /**
     * 登录密码
     */
    private static final String PASSWORD;

    static {
        //加载jdbc.properties 配置文件
        InputStream in = JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
        //如果没有找到文件
        if (in == null){
            throw  new RuntimeException("数据库配置文件没有找到");
        }
        //创建属性文件对象
        Properties prop = new Properties();
        try {
            prop.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //为数据连接属性赋值
        DRIVER = prop.getProperty("jdbc.driver");
        URL = prop.getProperty("jdbc.url");
        USERNAME = prop.getProperty("jdbc.username");
        PASSWORD = prop.getProperty("jdbc.password");
        //加载驱动
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接对象
     * @return
     */
    public static Connection getConn(){
        Connection connection = null;

        try {
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return  connection;
    }

    /**
     * 释放资源
     * @param connection
     * @param prep
     */
    public  static void close(Connection connection, PreparedStatement prep){
        if (prep != null){
            try {
                prep.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (connection != null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }


    /**
     * 释放资源
     * @param conn
     * @param prep
     * @param rs
     */
    public  static void close(Connection conn, PreparedStatement prep, ResultSet rs){
        if (rs != null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        close(conn,prep);
    }
}
